package com.atguigu.tingshu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.config.WxPayV3Config;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.pattern.PayStrategy;
import com.atguigu.tingshu.order.pattern.TradeStrategy;
import com.atguigu.tingshu.order.pattern.factory.PayStrategyFactory;
import com.atguigu.tingshu.order.pattern.factory.TradeStrategyFactory;
import com.atguigu.tingshu.order.service.OrderDerateService;
import com.atguigu.tingshu.order.service.OrderDetailService;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.payment.PaymentFeignClient;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.atguigu.tingshu.vo.album.TrackStatVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.CloseOrderRequest;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AlbumFeignClient albumFeignClient;
    @Autowired
    private AccountFeignClient accountFeignClient;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderDerateService orderDerateService;
    @Autowired
    private TradeStrategyFactory tradeStrategyFactory;
    @Autowired
    private PayStrategyFactory payStrategyFactory;
    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;
    @Autowired
    private WxPayV3Config wxPayV3Config;
    @Autowired
    private PaymentFeignClient paymentFeignClient;


    /**
     * 三种商品（VIP会员、专辑、声音）订单结算,渲染订单结算页面
     *
     * @param tradeVo (购买项目类型、购买项目ID、声音数量)
     * @return 订单VO信息
     */
    @Override
    public OrderInfoVo trade(Long userId,TradeVo tradeVo) {
        //策略模式+工厂模式对代码进行优化
        //根据类型从工厂中获取到对应的策略实现类对象
        TradeStrategy tradeStrategy = tradeStrategyFactory.getTradeStrategy(tradeVo.getItemType());
        //调用策略实现类对象对应的发货业务
        OrderInfoVo orderInfoVo = tradeStrategy.trade(userId, tradeVo);

//        //创建返回结果对象
//        OrderInfoVo orderInfoVo = new OrderInfoVo();
//        //创建订单明细列表
//        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
//        //创建订单减免明细列表
//        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();
//        //声明金额相关变量
//        BigDecimal originPrice = new BigDecimal("0.00");
//        BigDecimal discountPrice = new BigDecimal("0.00");
//        BigDecimal derateAmount = new BigDecimal("0.00");
//
//        //判断付款项目类型: 1001-专辑 1002-声音 1003-vip会员
//        if(SystemConstant.ORDER_ITEM_TYPE_VIP.equals(tradeVo.getItemType())){
//            //如果付款项目为vip会员
//            //调用远程服务根据付款项目id获取到具体的vip套餐
//            VipServiceConfig vipServiceConfig = userFeignClient.getVipServiceConfig(tradeVo.getItemId()).getData();
//            Assert.notNull(vipServiceConfig,"vip会员套餐id:{}为null",tradeVo.getItemId());
//
//            //根据原始金额-实际金额计算减免金额
//            originPrice = vipServiceConfig.getPrice(); //原始价格
//            discountPrice = vipServiceConfig.getDiscountPrice(); //实际价格
//            if(originPrice.compareTo(discountPrice) == 1){
//                derateAmount = originPrice.subtract(discountPrice);
//            }
//
//            //声明订单明细对象,添加到订单明细列表
//            OrderDetailVo orderDetailVo = new OrderDetailVo();
//            orderDetailVo.setItemId(vipServiceConfig.getId());
//            orderDetailVo.setItemName("会员套餐：" + vipServiceConfig.getName());
//            orderDetailVo.setItemPrice(originPrice);
//            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
//            orderDetailVoList.add(orderDetailVo);
//
//            //如果有优惠,封装订单减免vo对象,加入到订单减免列表
//            if(originPrice.compareTo(discountPrice) == 1){
//                OrderDerateVo orderDerateVo = new OrderDerateVo();
//                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT); //订单减免类型 1405-专辑折扣 1406-VIP服务折
//                orderDerateVo.setDerateAmount(derateAmount);
//                orderDerateVo.setRemarks("套餐限时减免：" + derateAmount);
//                orderDerateVoList.add(orderDerateVo);
//            }
//
//
//        }else if(SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(tradeVo.getItemType())){
//            //如果付款项目为专辑
//            //调用远程服务查看该专辑是否已被此用户购买
//            Boolean isPaid = userFeignClient.isPaidAlbum(tradeVo.getItemId()).getData();
//            Assert.notNull(isPaid,"【用户服务】提供isPaidAlbum远程调用失败");
//            if(isPaid) {
//                throw new GuiguException(500, "用户已经购买此专辑");
//            }
////            Assert.isFalse(isPaid,"用户已经购买此专辑{}",tradeVo.getItemId()); //等同上面的if判断
//            //调用远程服务查看专辑相关信息(价格，折扣等)
//            AlbumInfo albumInfo = albumFeignClient.getAlbumInfoById(tradeVo.getItemId()).getData();
//            Assert.notNull(albumInfo,"查看专辑失败,id:{}",tradeVo.getItemId());
//
//            //设置价格信息
//            originPrice = albumInfo.getPrice(); //原价
//            //折扣信息
//            BigDecimal discount = albumInfo.getDiscount();
//            BigDecimal vipDiscount = albumInfo.getVipDiscount();
//            //调用远程服务获取用户信息 并计算实际价格和优惠价格
//            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
//            Assert.notNull(userInfoVo,"用户id:{}不存在",userId);
//            Boolean isVIP = false;
//            if(userInfoVo.getIsVip().intValue() == 1 && userInfoVo.getVipExpireTime().after(new Date())){
//                isVIP = true;
//            }
//            //基于用户身份计算专辑实际价格
//            if(isVIP && vipDiscount.doubleValue() != -1){
//                //如果该用户是vip且专辑有折扣   "0.1-9.9  不打折 -1"
//                discountPrice = originPrice.multiply(vipDiscount).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
//            }
//            if(!isVIP && discount.doubleValue() != -1){
//                //如果该用户不是vip且专辑有折扣  "0.1-9.9  不打折 -1"
//                discountPrice = originPrice.multiply(discount).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
//            }
//            //优惠价格
//            derateAmount = originPrice.subtract(discountPrice);
//            //声明订单详情对象 加入到订单明细列表
//            OrderDetailVo orderDetailVo = new OrderDetailVo();
//            orderDetailVo.setItemId(albumInfo.getId());
//            orderDetailVo.setItemName("专辑: " + albumInfo.getAlbumTitle());
//            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
//            orderDetailVo.setItemPrice(originPrice);
//            orderDetailVoList.add(orderDetailVo);
//
//            //如果有优惠,封装订单减免vo对象,加入到订单减免列表
//            if(originPrice.compareTo(discountPrice) == 1){
//                OrderDerateVo orderDerateVo = new OrderDerateVo();
//                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
//                orderDerateVo.setDerateAmount(derateAmount);
//                orderDerateVo.setRemarks("专辑折扣减免: " + derateAmount);
//                orderDerateVoList.add(orderDerateVo);
//            }
//
//        }else if(SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(tradeVo.getItemType())){
//            //如果付款项目为声音
//            //远程调用获取待购买声音列表
//            List<TrackInfo> trackInfoList = albumFeignClient.findPaidTrackInfoList(tradeVo.getItemId(), tradeVo.getTrackCount()).getData();
//            Assert.notNull(trackInfoList,"没有需要结算的声音");
//
//            //调用远程方法获取专辑信息  从专辑信息中获取到单价-声音不支持折扣
//            AlbumInfo albumInfo = albumFeignClient.getAlbumInfoById(trackInfoList.get(0).getAlbumId()).getData();
//            Assert.notNull(albumInfo, "专辑{}不存在", trackInfoList.get(0).getAlbumId());
//            BigDecimal price = albumInfo.getPrice(); //单价
//            //计算相关价格数据
//            originPrice = price.multiply(new BigDecimal(trackInfoList.size()));
//            discountPrice = originPrice;
//
//            //声明订单明细vo对象,加入到订单明细列表
//            orderDetailVoList = trackInfoList.stream().map(o -> {
//                OrderDetailVo orderDetailVo = new OrderDetailVo();
//                orderDetailVo.setItemId(o.getId());
//                orderDetailVo.setItemName("声音: " + o.getTrackTitle());
//                orderDetailVo.setItemUrl(o.getCoverUrl());
//                orderDetailVo.setItemPrice(price); //单价
//                return orderDetailVo;
//            }).collect(Collectors.toList());
//        }

        //封装返回的结果对象
        //将订单流水号存入到缓存中,避免用户重复提交订单
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        String tradeNo = IdUtil.randomUUID();
        redisTemplate.opsForValue().set(tradeKey,tradeNo,RedisConstant.ORDER_TRADE_EXPIRE, TimeUnit.MINUTES);
        orderInfoVo.setTradeNo(tradeNo); //订单流水号

//        orderInfoVo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN); //支付方式 此处不需要设置支付方式
//        orderInfoVo.setItemType(tradeVo.getItemType()); //付款项目类型: 1001-专辑 1002-声音 1003-vip会员
//        orderInfoVo.setOriginalAmount(originPrice);  //原价
//        orderInfoVo.setDerateAmount(derateAmount);   //优惠价
//        orderInfoVo.setOrderAmount(discountPrice);   //实际价
//        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
//        orderInfoVo.setOrderDerateVoList(orderDerateVoList);

        long currentTimeMillis = System.currentTimeMillis();
        orderInfoVo.setTimestamp(currentTimeMillis);  //时间戳

        //将vo对象转为map
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo, false, true);
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign); //签名 防止订单数据被恶意篡改，确保数据完整性和来源可信性

        return orderInfoVo;
    }

    /**
     * 提交订单
     *
     * @param vo
     * @return
     */
    @Override
//    @GlobalTransactional(rollbackFor = Exception.class)
    public Map<String, String> submitOrder(Long userId, OrderInfoVo vo) {
        //首先验证流水号  避免用户重复提交
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //通过lua脚本保证原子性
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        RedisScript<Boolean> redisScript = new DefaultRedisScript<>(script,Boolean.class);
        Boolean isFlag = (Boolean) redisTemplate.execute(redisScript, Arrays.asList(tradeKey), vo.getTradeNo());
        if(!isFlag){
            log.error("验证流水号失败");
            throw new GuiguException(500,"验证流水号失败");
        }
        //验证签名，防止在前端时业务数据被篡改
        Map<String, Object> map = BeanUtil.beanToMap(vo);
        map.remove("payWay");
        SignHelper.checkSign(map);

        //保存订单
        OrderInfo orderInfo = this.saveOrderInfo(userId,vo);
        //获取到支付方式
        String payWay = vo.getPayWay();

        //通过策略模式+工厂模式优化代码
        //根据类型从工厂中获取到对应的策略实现类对象
        PayStrategy payStrategy = payStrategyFactory.getPayStraategy(payWay);
        payStrategy.submitOrder(userId,orderInfo);

//        //模拟出现异常
//        if(true){
//            int i = 1 / 0;
//
//        }
//        if(SystemConstant.ORDER_PAY_WAY_WEIXIN.equals(payWay)){
//            //微信支付
//
//        }else if(SystemConstant.ORDER_PAY_ACCOUNT.equals(payWay)){
//            //余额支付
//            //远程调用扣减账户余额 AccountDeductVo
//            AccountDeductVo accountDeductVo = new AccountDeductVo();
//            accountDeductVo.setOrderNo(orderInfo.getOrderNo());
//            accountDeductVo.setUserId(orderInfo.getUserId());
//            accountDeductVo.setAmount(orderInfo.getOrderAmount());
//            accountDeductVo.setContent(orderInfo.getOrderTitle());
//
//            Result result = accountFeignClient.checkAndDeduct(accountDeductVo);
//            if(result.getCode().intValue() != 200){
//                // 扣减余额失败，业务终止，回滚全局事务
//                throw new GuiguException(result.getCode(), result.getMessage());
//            }
//            //扣减余额成功 将数据库中的订单信息进行修改
//            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
//            orderInfoMapper.updateById(orderInfo);
//
//            //支付成功后调用远程服务进行虚拟发货
//            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
//            userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
//            userPaidRecordVo.setUserId(orderInfo.getUserId());
//            userPaidRecordVo.setItemType(orderInfo.getItemType());
//            List<OrderDetail> orderDetailList = orderDetailService.list(
//                    new LambdaQueryWrapper<OrderDetail>()
//                            .eq(OrderDetail::getOrderId, orderInfo.getId())
//                            .select(OrderDetail::getItemId)
//            );
//            List<Long> itemIdList = orderDetailList.stream().map(OrderDetail::getItemId).collect(Collectors.toList());
//            userPaidRecordVo.setItemIdList(itemIdList);
//
//            if(!CollectionUtils.isEmpty(orderDetailList)){
//
//                result = userFeignClient.savePaidRecord(userPaidRecordVo);
//                if(result.getCode().intValue() != 200){
//                    log.error("虚拟发货失败");
//                    throw new GuiguException(result.getCode(),result.getMessage());
//                }
//            }
//        }

        return Map.of("orderNo",orderInfo.getOrderNo());
    }

    /**
     * 保存订单相关信息
     * @param userId
     * @param vo
     * @return
     */
    @Override
    public OrderInfo saveOrderInfo(Long userId, OrderInfoVo vo) {
        //封装订单基础信息
        OrderInfo orderInfo = BeanUtil.copyProperties(vo, OrderInfo.class);
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(DateUtil.today().replaceAll("-","") + IdUtil.getSnowflakeNextId());
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);
        List<OrderDetailVo> orderDetailVoList = vo.getOrderDetailVoList();
        if(!CollectionUtils.isEmpty(orderDetailVoList)){
            orderInfo.setOrderTitle(orderDetailVoList.get(0).getItemName());
        }
        //将订单信息插入订单信息表 回显得到id
        orderInfoMapper.insert(orderInfo);
        Long orderInfoId = orderInfo.getId();


        //订单详情表
        if(!CollectionUtils.isEmpty(orderDetailVoList)){
            List<OrderDetail> orderDetailList = orderDetailVoList.stream().map(o -> {
                OrderDetail orderDetail = BeanUtil.copyProperties(o, OrderDetail.class);
                orderDetail.setOrderId(orderInfoId);
                return orderDetail;
            }).collect(Collectors.toList());
            //插入订单详情数据
            orderDetailService.saveBatch(orderDetailList);
        }

        List<OrderDerateVo> orderDerateVoList = vo.getOrderDerateVoList();
        if(!CollectionUtils.isEmpty(orderDerateVoList)){
            List<OrderDerate> orderDerateList = orderDerateVoList.stream().map(o -> {
                OrderDerate orderDerate = BeanUtil.copyProperties(o, OrderDerate.class);
                orderDerate.setOrderId(orderInfoId);
                return orderDerate;
            }).collect(Collectors.toList());
            //插入优惠明细
            orderDerateService.saveBatch(orderDerateList);
        }

        return orderInfo;
    }

    /**
     * 根据订单编号查询订单信息（包含明细） 考虑到在支付成功后收到微信异步回调需要获取订单信息固该接口不需要登录访问
     *
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getOrderInfo(String orderNo) {
        //根据订单编号查询订单基础信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getOrderNo, orderNo)
        );
        if(orderInfo == null){
            throw new GuiguException(500,"无此订单号的订单!");
        }
        //根据订单号查询订单详情
        List<OrderDetail> orderDetailList = orderDetailService.list(
                new LambdaQueryWrapper<OrderDetail>()
                        .eq(OrderDetail::getOrderId, orderInfo.getId())
        );
        //根据订单号查询优惠详情
        List<OrderDerate> orderDerateList = orderDerateService.list(
                new LambdaQueryWrapper<OrderDerate>()
                        .eq(OrderDerate::getOrderId, orderInfo.getId())
        );
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.setOrderDerateList(orderDerateList);
//        orderInfo.setPayWayName(orderInfo.getPayWayName());
//        orderInfo.setOrderStatusName(orderInfo.getOrderStatusName());

        return orderInfo;
    }


    /**
     * 查询当前用户订单列表(新写法：对比原写法减少了查询次数(订单详情和优惠详情的查询从2N次减少到2次))
     *
     * @param userId
     * @param pageInfo
     * @return
     */
    @Override
    public Page<OrderInfo> findUserPage(Page<OrderInfo> infoPage, Long userId) {
        //根据用户id查询订单列表
        Page<OrderInfo> pageOrderInfo = orderInfoMapper.selectPage(infoPage,
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getUserId, userId)
                        .orderByDesc(OrderInfo::getId)
                        .select(OrderInfo::getId,OrderInfo::getOrderNo,OrderInfo::getOrderStatus,
                                OrderInfo::getPayWay,OrderInfo::getOriginalAmount,OrderInfo::getOrderAmount,
                                OrderInfo::getDerateAmount)
        );

        //获取到所有的订单号
        List<Long> orderIdList = pageOrderInfo.getRecords().stream()
                .map(OrderInfo::getId).collect(Collectors.toList());

        //根据订单号查询所有的订单明细
        List<OrderDetail> orderDetails = orderDetailService.list(
                new LambdaQueryWrapper<OrderDetail>()
                        .in(OrderDetail::getOrderId, orderIdList)
        );
        //根据订单号查询所有的优惠明细
        List<OrderDerate> orderDerates = orderDerateService.list(
                new LambdaQueryWrapper<OrderDerate>()
                        .in(OrderDerate::getOrderId, orderIdList)
        );

        //将详情明细按照订单id进行分组
        if(!CollectionUtils.isEmpty(orderDetails)){  //CollectionUtil.isNotEmpty(orderDetails)
            Map<Long, List<OrderDetail>> orderDetailMap = orderDetails.stream()
                    .collect(Collectors.groupingBy(OrderDetail::getOrderId));
            //如果详情不为空则封装属性
            if(!CollectionUtils.isEmpty(orderDetailMap)){
                pageOrderInfo.getRecords().stream().forEach(o -> {
                    o.setOrderDetailList(orderDetailMap.get(o.getId()));
                });
            }
        }

        //将优惠明细按照订单id进行分组
        if(!CollectionUtils.isEmpty(orderDerates)){  //CollectionUtil.isNotEmpty(orderDerates)
            Map<Long, List<OrderDerate>> orderDerateMap = orderDerates.stream()
                    .collect(Collectors.groupingBy(OrderDerate::getOrderId));
            //如果优惠明细不为空,则封装属性
            if(!CollectionUtils.isEmpty(orderDerateMap)){
                pageOrderInfo.getRecords().stream().forEach(o -> {
                    o.setOrderDerateList(orderDerateMap.get(o.getId()));
                });
            }
        }
        return pageOrderInfo;
    }

    /**
     * 根据订单id取消指定的订单
     * @param orderId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long orderId) {
        //根据id查询到订单信息
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(orderInfo != null){
            //判断订单当前状态
            if(SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())){
                //如果当前订单状态为 未支付  则将订单状态设置为取消 并更新订单信息
                orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
                orderInfoMapper.updateById(orderInfo);

                // 关闭第三方支付平台(微信支付)支付订单
                // 初始化服务
                JsapiService service = new JsapiService.Builder().config(rsaAutoCertificateConfig).build();
                //关闭订单
                CloseOrderRequest request = new CloseOrderRequest();
                //调用远程支付服务获取到paymentInfo
                PaymentInfo paymentInfo = paymentFeignClient.getOutOrderNo(SystemConstant.PAYMENT_TYPE_ORDER, orderInfo.getOrderNo()).getData();
                Assert.notNull(paymentInfo,"查询订单流水号:{}的支付信息为空",orderInfo.getOrderNo());
                request.setOutTradeNo(paymentInfo.getOutTradeNo());
                request.setMchid(wxPayV3Config.getMerchantId());

                service.closeOrder(request);
            }
        }
    }

    /**
     * 用户付款成功后，处理订单相关业务
     * @param orderNo
     * @return
     */
    @Override
    public void orderPaySuccess(String orderNo) {
        //根据订单流水号获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getOrderNo, orderNo)
        );
        //判断订单状态: 0901-未支付 0902-已支付 0903-已取消
        if(SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())){
            //将订单状态修改为已支付
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            //更新订单信息
            orderInfoMapper.updateById(orderInfo);

            //支付成功后进行虚拟物品发货
            //构建虚拟发货对象 UserPaidRecordVo
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            userPaidRecordVo.setUserId(orderInfo.getUserId());
            userPaidRecordVo.setOrderNo(orderNo);
            userPaidRecordVo.setItemType(orderInfo.getItemType());

            //查询订单明细得到购买项目id列表
            List<OrderDetail> orderDetailList = orderDetailService.list(
                    new LambdaQueryWrapper<OrderDetail>()
                            .eq(OrderDetail::getOrderId, orderInfo.getId())
                            .select(OrderDetail::getItemId)
            );
            List<Long> itemIdList = orderDetailList.stream()
                    .map(OrderDetail::getItemId).collect(Collectors.toList());
            userPaidRecordVo.setItemIdList(itemIdList);
            //调用远程服务 - 虚拟发货
            Result result = userFeignClient.savePaidRecord(userPaidRecordVo);
            if(result.getCode().intValue() != 200){
                throw new GuiguException(result.getCode(), result.getMessage());
            }
        }
    }


    /**
     * 查询当前用户订单列表(原写法)
     *
     * @param userId
     * @param pageInfo
     * @return
     */
//    @Override
    public Page<OrderInfo> findUserPage1(Page<OrderInfo> infoPage, Long userId) {
        //根据用户id查询订单列表
        Page<OrderInfo> pageOrderInfo = orderInfoMapper.selectPage(infoPage,
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getUserId, userId)
        );

        if(!CollectionUtils.isEmpty(pageOrderInfo.getRecords())){
            //查询订单详情信息,并封装到订单列表中
            pageOrderInfo.getRecords().stream().forEach(o -> {
                List<OrderDetail> list = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>()
                        .eq(OrderDetail::getOrderId, o.getId()));
                o.setOrderDetailList(list);
            });
            //查询订单优惠信息,并封装到订单列表中
            pageOrderInfo.getRecords().forEach(o -> {
                List<OrderDerate> list = orderDerateService.list(new LambdaQueryWrapper<OrderDerate>()
                        .eq(OrderDerate::getOrderId, o.getId()));
                o.setOrderDerateList(list);
            });

        }
        return pageOrderInfo;
    }
}
